<?php

namespace apiend\modules\course\models;

use Yii;
use yii\data\ActiveDataProvider;
use common\models\course\Course;
use common\helpers\Url;

/**
 * This is the model class for table "{{%dynamic}}".
 *
 * @property int $id
 * @property string $user_id 用户ID
 * @property string $content
 * @property int $direction 动态类型：0主动动态，1被动动态
 * @property int $retweet_id 转发动态原始ID
 * @property int $status
 * @property string $created_at
 * @property string $updated_at
 * @property string $deleted_at
 */
class RecommendCourseSearch extends \common\models\course\RecommendCourse {

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params = []) {
        $query = static::find()
        ->alias('t')
        ->where([
            't.status' => static::STATUS_ACTIVE,
        ])->orderBy([
            't.weight' => SORT_DESC,
            't.listorder' => SORT_ASC,
        ]);
        $query->joinWith('course c', true, 'INNER JOIN')
        ->andWhere([
            'c.status' => Course::STATUS_ACTIVE,
            'c.audit_status' => Course::AUDIT_STATUS_ACTIVE,
        ]);

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
            'pagination' => [
                'pageSize' => 6,
            ],
        ]);

        Yii::$app->db->cache(function($db) use($dataProvider) {
            $dataProvider->prepare();
        }, 60);

        return $dataProvider;
    }

    public function fields() {
        return [
            'id' => 'course_id',
            'name' => function () {
                return $this->course->name;
            },
            'thumb' => function () {
                return $this->course->thumb;
            },
            'begintime' => function () {
                return date('Y-m-d', $this->course->begin_time);
            },
            'teacher' => function () {
                if ($this->course->teacher) {
                    return $this->course->teacher->name;
                }
                return '待定';
            },
            'price' => function () {
                return $this->course->price;
            },
            'link' => function () {
                return Url::h5('/course/' . $this->course_id);
            },
        ];
    }

}
